<template>
  <div class="wrap">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card 视图区 -->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="addRolesVisible = true"
          >添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table
        :data="rolesListD"
        border
        style="width: 100%; margin-top: 15px"
        max-height="700"
      >
        <!-- 展开行 -->
        <el-table-column type="expand" align="center" width="50">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="item in scope.row.children"
              :key="item.id"
              class="bottom_Border"
            >
              <!-- 一级权限名称 -->
              <el-col :span="5">
                <el-tag closable @close="delectRightTage(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right" />
              </el-col>
              <!-- 二 三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="value in item.children"
                  :key="value.id"
                  class="twoRights"
                >
                  <el-col :span="6">
                    <!-- 二级权限名称 -->
                    <el-tag
                      type="success"
                      closable
                      @close="delectRightTage(scope.row, value.id)"
                    >{{ value.authName }}</el-tag>
                    <i class="el-icon-caret-right" />
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <!-- 三级权限名称 -->
                    <el-tag
                      v-for="t in value.children"
                      :key="t.id"
                      type="warning"
                      closable
                      @close="delectRightTage(scope.row, t.id)"
                    >
                      {{ t.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" align="center" width="50" />
        <el-table-column
          prop="roleName"
          label="角色名称"
          align="center"
          width="180"
        />
        <el-table-column prop="roleDesc" label="角色描述" align="center" />
        <el-table-column label="操作" width="400" align="center">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="small"
              type="warning"
              icon="el-icon-s-tools"
              @click="showRightsDialog(scope.row)"
            >分配权限</el-button>
            <el-button
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色弹出框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRolesVisible"
        @close="cancleAddRoles()"
      >
        <el-form
          ref="rolesFormRef"
          :model="addRolesForm"
          label-width="80px"
          :rules="rolesRules"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName" />
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancleAddRoles">取 消</el-button>
          <el-button type="primary" @click="confirmAddRoles">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限弹出框 -->

      <el-dialog
        title="分配权限"
        :visible.sync="showRightVisible"
        @close="cancleShowRight()"
      >
        <div class="tree_class">
          <el-tree
            ref="tree"
            :props="defaultProps"
            :data="rightsList"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="defaultKey"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancleShowRight">取 消</el-button>
          <el-button type="primary" @click="comfirmShowRight">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import {
  rolesList,
  addRolesApi,
  getRolesApi,
  editRolesApi,
  deleteRolesApi,
  getRightsList,
  deleteRolesRight,
  showRolesRights
} from '@/api/roles.js';
export default {
  name: 'Roles',
  components: {},
  data() {
    return {
      rolesId: '', // (当前选中的角色id)
      defaultKey: [], // 默认选中的节点
      rightsList: [], // 权限列表数据
      defaultProps: {
        // 权限树的配置项
        children: 'children',
        label: 'authName'
      },
      // 分配权限弹出框是否可见
      showRightVisible: false,
      // 添加角色表单
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 角色校验
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      addRolesVisible: false, // 添加dialog是否显示
      rolesListD: [] // 角色列表
    };
  },
  mounted() {
    this.getRolesList();
  },
  methods: {
    /* 分配权限确定 */
    comfirmShowRight() {
      /* 获取到所有被选中的和半选中的 id */
      const rightIdArr = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ];
      // 传给后端的参数是字符串
      const rids = rightIdArr.join(',');
      showRolesRights(this.rolesId, { rids }).then((res) => {
        const { msg, status } = res.data.meta;
        if (status !== 200) return this.$message.error(msg);
        this.getRolesList();
        this.showRightVisible = false;
        this.$message.success('更新成功！');
      }).catch((err) => {
        console.log(err);
      });
    },
    /* 取消分配权限 */
    cancleShowRight() {
      this.defaultKey = [];
      this.rolesId = '';
      this.showRightVisible = false;
    },
    /* 分配权限  value 是当前角色对象*/
    showRightsDialog(value) {
      this.rolesId = value.id;
      // 获取所有权限的数据
      getRightsList('tree').then((res) => {
        const { msg, status } = res.data.meta;
        if (status !== 200) return this.$message.error(msg);
        this.rightsList = res.data.data;
        /* 通过递归获取当前角色身上三级权限,（三级权限都显示了,一级二级自然会跟着显示）然后进行回显 */
        this.getDefaultKeyId(value, this.defaultKey);
        this.showRightVisible = true;
      });
    },
    /* 获取默认选中权限的 id */
    getDefaultKeyId(rolesArr, arr) {
      if (!rolesArr.children) {
        return arr.push(rolesArr.id);
      }
      rolesArr.children.forEach((item) => {
        this.getDefaultKeyId(item, arr);
      });
    },
    /* 删除角色指定权限 */
    delectRightTage(row, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRolesRight(row.id, rightId).then((res) => {
            const { msg, status } = res.data.meta;
            if (status !== 200) return this.$message.error(msg);
            /* 这里我们是通过参数的方式进行赋值操作，
              只有数组和对象我们通过参数的方式，进行操作(添加、删除、修改)的时候可以改变源数据
            */
            row.children = res.data.data;
            this.$message.success('删除成功!');
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    /* 删除角色 */
    deleteRoles(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRolesApi(id).then(() => {
            this.getRolesList();
            this.$message.success('删除成功!');
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 点击编辑查看角色
    editRoles(id) {
      getRolesApi(id).then((res) => {
        const { msg, status } = res.data.meta;
        if (status !== 200) return this.$message.error(msg);
        this.addRolesForm = res.data.data;
        this.addRolesVisible = true;
      });
    },
    /* 获取角色列表 */
    getRolesList() {
      rolesList()
        .then((res) => {
          const { msg, status } = res.data.meta;
          if (status !== 200) return this.$message.error(msg);
          this.rolesListD = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    /* 编辑角色 */
    editRolesWay() {
      editRolesApi(this.addRolesForm)
        .then((res) => {
          const { msg, status } = res.data.meta;
          if (status !== 200) return this.$message.error(msg);
          this.getRolesList();
          this.$message.success('编辑成功！');
          this.addRolesVisible = false;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    /* 角色dialog确定 */
    confirmAddRoles() {
      this.$refs.rolesFormRef.validate((valid) => {
        if (!valid) return false;
        // 添加角色 网络请求
        if (this.addRolesForm.roleId) {
          // 编辑
          this.editRolesWay();
        } else {
          // 添加
          this.addRoles();
        }
      });
    },
    /* 关闭添加角色dialog */
    cancleAddRoles() {
      this.$refs.rolesFormRef.resetFields();
      this.addRolesVisible = false;
      this.addRolesForm = {
        roleName: '',
        roleDesc: ''
      };
    },
    /* 添加角色 */
    addRoles() {
      addRolesApi(this.addRolesForm)
        .then((res) => {
          const { msg, status } = res.data.meta;
          if (status !== 201) return this.$message.error(msg);
          this.getRolesList();
          this.$message.success('添加成功！');
          this.addRolesVisible = false;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    }
  }
};
</script>
<style scoped lang='scss'>
.el-tag {
  margin: 10px;
}
.el-row {
  display: flex;
  align-items: center;
}
.bottom_Border {
  border-bottom: 1px solid #eee;
}
.bottom_Border:nth-child(1) {
  border-top: 1px solid #eee;
}
.twoRights {
  &:not(:last-child) {
    border-bottom: 1px solid #eee;
  }
}
.tree_class {
  max-height: 400px;
  overflow-y: auto;
}
</style>
